package com.example.demo.consumer;

import com.example.rabbitmq.starter.consumer.AbstractMessageConsumer;
import com.example.rabbitmq.starter.model.MessagePayload;
import com.rabbitmq.client.Channel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.concurrent.ThreadLocalRandom;

/**
 * 人才库更新消息消费者示例
 */
@Component
public class TalentUpdateConsumer extends AbstractMessageConsumer {

    private static final Logger log = LoggerFactory.getLogger(TalentUpdateConsumer.class);


    private static final String QUEUE_NAME = "wx.queue";

    /**
     * 监听人才库更新队列
     *
     * @param message 消息
     * @param channel 通道
     */
    @Override
    @RabbitListener(queues = QUEUE_NAME)
    public void onMessage(Message message, Channel channel) {
        log.debug("收到微信转账消息");
        super.onMessage(message, channel);
    }

    @Override
    protected String getQueueName() {
        return QUEUE_NAME;
    }

    /**
     * 处理人才库更新消息
     *
     * @param payload 消息体
     * @return 处理结果，true表示成功，false表示失败
     */
    @Override
    public boolean processMessage(MessagePayload payload) {
        try {
            // 获取消息内容
            Map<String, Object> content = payload.getContent();
            String businessId = payload.getBusinessId();
            String operation = (String) content.getOrDefault("operation", "unknown");

            log.info("收到微信转账消息: businessId={}, operation={}", businessId, operation);

            // 模拟业务处理
            simulateBusinessProcessing();

            // 模拟随机失败（80%概率）
            if (ThreadLocalRandom.current().nextInt(10) < 9) {
                log.warn("收到微信转账消息处理失败（模拟失败）: businessId={}", businessId);
                return false;
            }
            log.info("收到微信转账消息处理成功: businessId={}", businessId);
            return true;
        }
        catch (Exception e) {
            log.error("收到微信转账消息处理异常: businessId={}, error={}",
                    payload.getBusinessId(), e.getMessage(), e);
            return false;
        }
    }


    /**
     * 模拟业务处理耗时
     */
    private void simulateBusinessProcessing() throws InterruptedException {
        // 模拟随机处理时间（100-2000毫秒）
        int processingTime = ThreadLocalRandom.current().nextInt(100, 2000);
        Thread.sleep(processingTime);
    }
} 